package com.pansoft.openplanet.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.core.xml.StubObject;
import com.efounder.chat.activity.ChatWebViewActivity;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.service.Registry;
import com.efounder.widget.commonviewpage.CircleIndicatorView;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.DialogViewpagerAdapter;
import com.pansoft.openplanet.bean.DialogBean;
import com.utilcode.util.ActivityUtils;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

/**
 * 首页广告信息弹窗跳转
 * Author by cimu
 * Date on 2019/1/7.
 */
public class AdvertisingDialogFragment extends DialogFragment {
    private View mView;
    private ImageView ivDialogCancel;
    private ViewPager vpDialogViewpager;
    private List<View> viewList;
    private DialogViewpagerAdapter adapter;
    private CircleIndicatorView mCircleIndicatorView;
    private List<String> imageArray = new ArrayList<>();
    private Class<?> clazz = null;
    private String goodId = "";
    private int mCurrentPosition = 0;
    private FrameLayout dialogFramLayout;
    private int screenWidth, screenHeight;
    List<DialogBean> dialogBeans;

    /**
     * 标记app首次进入是否弹AdDialog的判断值  false 弹窗 true为不弹 每次重新进入弹窗  App不销毁不会弹窗
     */
    private static boolean isShow = false;

    //广告弹窗
    public static void showAdvertisingDialogFragment() {
        if(isShow){
            return;
        }
        List<StubObject> stubMenuList = Registry.getRegEntryList("recommend");
        if (stubMenuList == null) {
            return;
        }
        ArrayList<DialogBean> dialogBeans = new ArrayList<>();

        dialogBeans.clear();
        for (StubObject stubObject : stubMenuList) {
            Hashtable<String, String> hashtable = stubObject.getStubTable();

            DialogBean dialogBean = new DialogBean();
            String filepath = AppConstant.APP_ROOT + "/res/unzip_res/Image/" + hashtable.get("menuIcon");
            dialogBean.setMenuIcon(filepath);
            dialogBean.setTitle(hashtable.get("title"));
            dialogBean.setId(hashtable.get("id"));
            dialogBean.setViewType(hashtable.get("viewType"));
            dialogBean.setAndroidShow(hashtable.get("AndroidShow"));
            dialogBean.setUrl(hashtable.get("url"));
            dialogBean.setGoodId(hashtable.get("goodId"));
            dialogBeans.add(dialogBean);
        }
        //广告弹窗
        if (dialogBeans.size() > 0) {
            AdvertisingDialogFragment advertisingDialogFragment = AdvertisingDialogFragment.newInstance(dialogBeans);
            if (ActivityUtils.getTopActivity() != null) {
                advertisingDialogFragment.show(((AppCompatActivity) ActivityUtils.getTopActivity()).getSupportFragmentManager(), "dialog_fragment");
                isShow = true;
            }
        } else {
            return;
        }
    }

    public static AdvertisingDialogFragment newInstance(ArrayList<DialogBean> dialogBeans) {

        Bundle args = new Bundle();
        args.putSerializable("dialogBeans", dialogBeans);
        AdvertisingDialogFragment fragment = new AdvertisingDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        dialogBeans = (List<DialogBean>) getArguments().getSerializable("dialogBeans");
        if (dialogBeans == null) {
            dismiss();
        }

        getDialog().setCanceledOnTouchOutside(false);
        //透明背景
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mView = LayoutInflater.from(getActivity()).inflate(R.layout.assets_fragment_dialog, container, false);
        initView();
        initData();
        if (dialogBeans.size() > 0) {
            clickImage();
        }
        return mView;
    }

    private void initView() {
        ivDialogCancel = mView.findViewById(R.id.dialog_cancel);
        vpDialogViewpager = mView.findViewById(R.id.dialog_viewpager);
        mCircleIndicatorView = mView.findViewById(R.id.indicator_view);
        dialogFramLayout = mView.findViewById(R.id.dialog_frame);
        ViewGroup.LayoutParams params = dialogFramLayout.getLayoutParams();
        params.width = screenWidth * 4 / 5;
        params.height = screenWidth * 4 / 5 * 13 / 10;
        dialogFramLayout.setLayoutParams(params);
        viewList = new ArrayList<View>();
        adapter = new DialogViewpagerAdapter(viewList);
        ivDialogCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    public void initData() {
        for (int i = 0; i < dialogBeans.size(); i++) {
            imageArray.add(dialogBeans.get(i).getMenuIcon());
            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setAdjustViewBounds(true);
            //加载图片
//            Glide.with(this).load(imageArray.get(i)).into(imageView);
            LXGlideImageLoader.getInstance().displayImage(this, imageView, imageArray.get(i));
            viewList.add(imageView);
        }
        //将图片填充
        for (int j = 0; j < imageArray.size(); j++) {
            if (imageArray.size() > 1) {
                mCircleIndicatorView.setVisibility(View.VISIBLE);
            } else {
                mCircleIndicatorView.setVisibility(View.GONE);
            }
        }
        vpDialogViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                // 把当前显示的position传递出去
                mCurrentPosition = position;
                clickImage();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vpDialogViewpager.setAdapter(adapter);
        mCircleIndicatorView.setUpWithViewPager(vpDialogViewpager);
    }

    public void clickImage() {
        if (dialogBeans.get(mCurrentPosition).getViewType().equals("display")) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            String androidShow = dialogBeans.get(mCurrentPosition).getAndroidShow();
            if (TextUtils.isEmpty(androidShow)) {
                return;
            }
            try {
                clazz = loader.loadClass(androidShow);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (clazz == null) {
                return;
            }
            goodId = dialogBeans.get(mCurrentPosition).getGoodId();
            viewList.get(mCurrentPosition).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), clazz);
                    intent.putExtra("goodbh", goodId);
                    getActivity().startActivity(intent);
                    dismiss();
                }
            });

        } else if (dialogBeans.get(mCurrentPosition).getViewType().equals("web")) {
            final String url = dialogBeans.get(mCurrentPosition).getUrl();
            viewList.get(mCurrentPosition).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ChatWebViewActivity.class);
                    try {
                        intent.putExtra("url", url);
                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                    getActivity().startActivity(intent);
                    dismiss();

                }
            });
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        dialogBeans.clear();
    }
}
